package com.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;

/**
 * 获取真实用户ip工具类
 *
 * @author Stone
 */
public class IpUtil {
    // TODO JAVA获取客户端IP地址和MAC地址
    // https://www.cnblogs.com/huangjian2/p/6238236.html

    /**
     * 获取登录用户IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "本地";
        }
        return ip;
    }

    /**
     * 根据网卡获取MAC地址
     *
     * @param ia
     * @return
     * @throws Exception
     */
    public static String getMACAddress(InetAddress ia) throws Exception {
        // 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        // 下面代码是把mac地址拼装成String
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        // 把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }

    /**
     * 根据ip地址获取MAC地址
     *
     * @param ip
     * @return
     */
    public static String getMACAddress(String ip) {
        String str = "";
        String macAddress = "";
        try {
            // Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            Process p = Runtime.getRuntime().exec("nbtscan -A " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf("MAC Address") > 1) {
                        macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }

    public static String getOsName() {
        String os = "";
        os = System.getProperty("os.name");
        return os;
    }

    public static String getMACAddress() {
        String address = "";
        String os = getOsName();
        if (os.startsWith("Windows")) {
            try {
                String command = "cmd.exe /c ipconfig /all";
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.indexOf("Physical Address") > 0) {
                        int index = line.indexOf(":");
                        index += 2;
                        address = line.substring(index);
                        break;
                    }
                }
                br.close();
                return address.trim();
            } catch (IOException e) {
            }
        } else if (os.startsWith("Linux")) {
            String command = "/bin/sh -c ifconfig -a";
            Process p;
            try {
                p = Runtime.getRuntime().exec(command);
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.indexOf("HWaddr") > 0) {
                        int index = line.indexOf("HWaddr") + "HWaddr".length();
                        address = line.substring(index);
                        break;
                    }
                }
                br.close();
            } catch (IOException e) {
            }
        }
        address = address.trim();
        return address;
    }

    public static void main(String[] args) throws IOException {
//		System.out.println("Operation System=" + getOsName());
//		System.out.println("Mac Address=" + getMACAddress());
        InetAddress inetAddress;// 声明InetAddress对象
        try {
            inetAddress = InetAddress.getLocalHost();// 实例化InetAddress对象，返回本地主机
            String hostName = inetAddress.getHostName();// 获取本地主机名
            String canonicalHostName = inetAddress.getCanonicalHostName();// 获取此IP地址的完全限定域名
            byte[] address = inetAddress.getAddress();// 获取原始IP地址
            int a = 0;
            if (address[3] < 0) {
                a = address[3] + 256;
            }
            String hostAddress = inetAddress.getHostAddress();// 获取本地主机的IP地址
            boolean reachable = inetAddress.isReachable(2000);// 获取布尔类型，看是否能到达此IP地址
            System.out.println(inetAddress.toString());
            System.out.println("主机名为：" + hostName);// 输出本地主机名
            System.out.println("此IP地址的完全限定域名：" + canonicalHostName);// 输出此IP地址的完全限定域名
            System.out.println("原始IP地址为：" + address[0] + "." + address[1] + "." + address[2] + "." + a);// 输出本地主机的原始IP地址
            System.out.println("IP地址为：" + hostAddress);// 输出本地主机的IP地址
            System.out.println("是否能到达此IP地址：" + reachable);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}